package com.liunian.utils;

import com.liunian.exceptions.NetworkException;
import lombok.extern.slf4j.Slf4j;

import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

@Slf4j
public class NetUtils {

    public static String getIp() throws NetworkException {
        try {
            // 获取所有的网卡信息
            Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
            while (enumeration.hasMoreElements()) {
                NetworkInterface networkInterface = enumeration.nextElement();
                // 过滤非回环接口和虚拟接口
                if (networkInterface.isLoopback() || networkInterface.isVirtual() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> en = networkInterface.getInetAddresses();
                while (en.hasMoreElements()) {
                    InetAddress address = en.nextElement();
                    // 过滤ipv6地址和回环地址
                    if (address instanceof Inet6Address || address.isLoopbackAddress()) {
                        continue;
                    }
                    String ipAddress = address.getHostAddress();
                    if (log.isDebugEnabled()) {
                        log.debug("局域网IP地址：{}", ipAddress);
                    }
                    return ipAddress;
                }
            }
            throw new NetworkException();
        } catch (SocketException e) {
            log.error("获取局域网IP时发生异常。",e);
            throw new NetworkException(e);
        }
    }
}